package vn.cuhanh;

import java.util.ArrayList;

import vn.cuhanh.fragment.AwardFragment;
import vn.cuhanh.fragment.CharacterInfoFragment;
import vn.cuhanh.fragment.HelpFragment;
import vn.cuhanh.fragment.HeroesFragment;
import vn.cuhanh.fragment.LeaderBoardFragment;
import vn.cuhanh.fragment.MenuFragment;
import vn.cuhanh.fragment.MinigameFragment;
import vn.cuhanh.fragment.NewsFragment;
import vn.cuhanh.fragment.PlayTypeFragment;
import vn.cuhanh.sys.UpdateHelper;
import vn.cuhanh.utils.HelperFunc;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.widget.Toast;

import com.viewpagerindicator.TitlePageIndicator;

public class GameDetailActivity extends BaseActivity {
	
	private static String[] CONTENT = new String[] {"Thông tin nhân vật", "Nhận quà", "Tin tức", "Kiểu chơi", "Tướng", "Minigame", "Bảng xếp hạng", "Hỗ trợ"};
	private static boolean[] LOGIN_REQUIRED_PAGE = new boolean[] {true, true, false, false, false, true, true, false};
	
	public static int DETAIL_PAGE_COUNT = 8;
	public static int[] availablePages;
	public static boolean forceRestartOnResume = false;
	private boolean doubleBackToExitPressedOnce = false;
	public static Context gameDetailContext;
	
	private ViewPager pager;
	private GameDetailPagerAdapter adapter;
	MenuFragment menuFragment;
	CharacterInfoFragment characterInfoFragment;
	AwardFragment awardFragment;
	NewsFragment newsFragment;
	PlayTypeFragment playTypeFragment;
	HeroesFragment heroesFragment;
	MinigameFragment minigameFragment;
	LeaderBoardFragment leaderBoardFragment;
	HelpFragment helpFragment;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		gameDetailContext = this;
		if(ChooseGameActivity.games == null) {
			ChooseGameActivity.games = HelperFunc.getListGame(this);
			ChooseGameActivity.current = ChooseGameActivity.games.get(0);
			MainActivity.doCheckUserLogin(this);
		}
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game_detail);
		setBehindContentView(R.layout.menu_frame);
		
		refreshAvailablePages();
		
		pager = (ViewPager) findViewById(R.id.pager);
		adapter = new GameDetailPagerAdapter(getSupportFragmentManager());
		pager.setAdapter(adapter);
		showPage(ChooseGameActivity.getPagePositionById(ChooseGameActivity.currentPage), false);
//		pager.setCurrentItem(ChooseGameActivity.getPagePositionById(ChooseGameActivity.currentPage));
		Log.d("on create game detail activity", "current page: " + ChooseGameActivity.currentPage);
		TitlePageIndicator pageIndicator = (TitlePageIndicator)findViewById(R.id.game_detail_page_indicator);
		pageIndicator.setViewPager(pager);
		pageIndicator.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				// TODO Auto-generated method stub
				if(position < availablePages.length) {
					ChooseGameActivity.currentPage = availablePages[position];
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		menuFragment = MenuFragment.getInstance(this);
		getSupportFragmentManager().beginTransaction().replace(R.id.menu_frame, menuFragment).commit();
		HelperFunc.showHashKey(this);
		UpdateHelper.checkForUpdate(this);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if(forceRestartOnResume) {
			forceRestartOnResume = false;
			restart();
			return;
		}
	}
	
	@Override
	public void onBackPressed() {
		if (doubleBackToExitPressedOnce) {
            finish();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            return;
        }
        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, getResources().getString(R.string.double_back_exist_message), Toast.LENGTH_SHORT).show();
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce=false;   
            }
        }, 2000);
	}
	
	public void restart() {
		Intent intent = new Intent(this, GameDetailActivity.class);
		startActivity(intent);
	}
	
	public void getUserInfoFailHandler() {
		MainActivity.isLogin = false;
		MainActivity.userAccount = null;
		MainActivity.userId = 0;
		MainActivity.username = "";
	}
	
	public static int[] getAvailablePages(int[] allPages) {
		if(MainActivity.isLogin) {
			return allPages;
		} 
		ArrayList<Integer> tmpList = new ArrayList<Integer>();
		for (int pageId : allPages) {
			if(! LOGIN_REQUIRED_PAGE[pageId - 1]) {
				tmpList.add(pageId);
			}
		}
		int[] result = new int[tmpList.size()];
		for(int i = 0; i < tmpList.size(); i++) {
			result[i] = tmpList.get(i);
		}
		return result;
	}
	
	public void refreshAvailablePages() {
		availablePages = getAvailablePages(ChooseGameActivity.current.getPages());
//		if(MainActivity.isLogin) {
//			availablePages = ;
//			return;
//		} 
//		int[] allPages = ChooseGameActivity.current.getPages();
//		ArrayList<Integer> tmpList = new ArrayList<Integer>();
//		for (int pageId : allPages) {
//			if(! LOGIN_REQUIRED_PAGE[pageId - 1]) {
//				tmpList.add(pageId);
//			}
//		}
//		availablePages = new int[tmpList.size()];
//		for(int i = 0; i < tmpList.size(); i++) {
//			availablePages[i] = tmpList.get(i);
//		}
	}
	
	public void showPage(int position) {
		showPage(position, true);
	}
	
	public void showPage(int position, boolean smoothScroll) {
		try {
			if(position < adapter.getCount()) {
				pager.setCurrentItem(position, smoothScroll);
			} else {
				HelperFunc.readStackTrace(new Exception("GameDetailActivity can't showPage " + position + ". Current page count is: " + adapter.getCount()));
			}
		} catch (Exception e) {
			restart();
		}
	}
	
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		MenuInflater inflater = getSupportMenuInflater();
//		inflater.inflate(R.menu.item_list, menu);
//		return true;
//	}
	
	public class GameDetailPagerAdapter extends FragmentPagerAdapter {

		public GameDetailPagerAdapter(FragmentManager fm) {
			super(fm);
			// TODO Auto-generated constructor stub
		}
		
		@Override
		public Fragment getItem(int position) {
			// TODO Auto-generated method stub
			int pageId = availablePages[position];
			switch (pageId) {
			case 1:
				if(characterInfoFragment == null) {
					characterInfoFragment = CharacterInfoFragment.newInstance(GameDetailActivity.this, 1); 
				}
				return characterInfoFragment;
			case 2:
				if(awardFragment == null) {
					awardFragment = AwardFragment.newInstance(GameDetailActivity.this); 
				}
				return awardFragment;
			case 3:
				if(newsFragment == null) {
					newsFragment = NewsFragment.newInstance(GameDetailActivity.this); 
				}
				return newsFragment;
			case 4:
				if(playTypeFragment == null) {
					playTypeFragment = PlayTypeFragment.newInstance(GameDetailActivity.this); 
				}
				return playTypeFragment;
			case 5:
				if(heroesFragment == null) {
					heroesFragment = HeroesFragment.newInstance(GameDetailActivity.this); 
				}
				return heroesFragment;
			case 6:
				if(minigameFragment == null) {
					minigameFragment = MinigameFragment.newInstance(GameDetailActivity.this); 
				}
				return minigameFragment;
			case 7:
				if(leaderBoardFragment == null) {
					leaderBoardFragment = LeaderBoardFragment.newInstance(GameDetailActivity.this); 
				}
				return leaderBoardFragment;
			default:
				if(helpFragment == null) {
					helpFragment = HelpFragment.newInstance(GameDetailActivity.this);
				}
				return helpFragment;
			}
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return availablePages.length;
//			if(ChooseGameActivity.current != null) {
//			} else {
//				return GameDetailActivity.DETAIL_PAGE_COUNT;
//			}
		}
		
		@Override
		public CharSequence getPageTitle(int position) {
			if(ChooseGameActivity.current != null) {
				return CONTENT[availablePages[position] - 1]; 
			} else {
				return CONTENT[position % CONTENT.length];
			}
		}
		
	}
}

